package com.mbengue.corp.apr.ra.beans;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

@ManagedBean(name = "validator")
@SessionScoped
public class FieldValidator implements Validator {
  @Override
  public void validate(FacesContext context, UIComponent component, Object value) throws ValidatorException {
    // Cast the value of the entered text to String.
    String text1 = (String) value;
    // Obtain the component and submitted value of the confirm text component.
    UIInput confirmComponent = (UIInput) component.getAttributes().get("confirm");
    String confirm = (String) confirmComponent.getSubmittedValue();
    // Check if they both are filled in.
    if (text1 == null || text1.isEmpty() || confirm == null || confirm.isEmpty()) {
      return; // Let required="true" do its job.
    }
    // Compare the text with the confirm text.
    if (!text1.equals(confirm)) {
      confirmComponent.setValid(false); // So that it's marked invalid.
      throw new ValidatorException(new FacesMessage(FacesMessage.SEVERITY_ERROR,
          "Les deux valeurs doivent être les mêmes !", ""));
    }
  }
}
